package com.grape.action.take_delivery;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;

import com.grape.action.common.BaseAction;
import com.grape.domain.take_delivery.WayBill;
import com.grape.service.take_delivery.WaybillService;

@Controller
@Namespace("/waybill")
@ParentPackage("json-default")
@Scope("prototype")
// controller必须放在Scope上面


public class WayBillAction extends BaseAction<WayBill> {
	private static final long serialVersionUID = 1L;
	private static final Logger l = Logger.getLogger(WayBill.class);

	@Autowired
	private WaybillService ws;
	
	// 运单数据回显
	@Action(value="findByWayBillNum",results=@Result(name="success",type="json"))
	public String findByWayBillNum() {
		WayBill wb = ws.findByWayBillNum(model.getWayBillNum());
		
		
		if (wb==null) {
			return NONE;
		}
		
		Map<String, Object> mp = new HashMap<>();
		mp.put("flag", true);
		mp.put("msg", wb);
		
		ServletActionContext.getContext().getValueStack().push(mp);
		return SUCCESS;
	}
	
	
	// 运单录入
	@Action(value = "save", results = @Result(name = "success", type = "json"))
	public String save() {
		
		// 保存结果返回
		Map<String, Object> mp = new HashMap<>();

		// 接收一个保存
			if (model.getWayBillNum()==null) {
				model.setWayBillNum(RandomStringUtils.randomNumeric(12));
			}
			
			String msg = ws.save(model);

			mp.put("msg", msg);
			l.info(msg);
			
		ServletActionContext.getContext().getValueStack().push(mp);
		return SUCCESS;
	}
	
	
	@Action(value="pageQuery",results=@Result(name="success",type="json"))
	public String pageQuery() {
		
		// 排个序真费劲
		Pageable pageable = new PageRequest(page-1,rows,new Sort(new Sort.Order(Sort.DEFAULT_DIRECTION.DESC,"id")));
		Page<WayBill> page = ws.pageQuery(pageable,model);
		
		pushPageDataToValueStack(page);
		return SUCCESS;
	}
	
	
}
